class HScrollbar
{
  int swidth, sheight;    // width and height of bar
  int xpos, ypos;         // x and y position of bar
  float spos, newspos;    // x position of slider
  int sposMin, sposMax;   // max and min values of slider
  boolean over;           // is the mouse over the slider?
  boolean locked;

  HScrollbar (int xp, int yp, int sw, int sh) {
    swidth = sw;
    sheight = sh;
    xpos = xp;
    ypos = yp-sheight/2;
    spos = xpos;
    newspos = spos;
    sposMin = xpos;
    sposMax = xpos + swidth - sheight ;

  }

  void update() {
    if(over()) {
      over = true;
    } else {
      over = false;
    }
    if(mousePressed && over) {
      locked = true;
    }
    if(!mousePressed) {
      locked = false;
    }
    if(locked) {
      newspos = constrain(mouseX-sheight/2, sposMin, sposMax);
    }
    spos = newspos;
  }

  int constrain(int val, int minv, int maxv) {
    return min(max(val, minv), maxv);
  }

  boolean over() {
    if(mouseX > xpos && mouseX < xpos+swidth &&
    mouseY > ypos-9 && mouseY < ypos+sheight+18) {
      return true;
    } else {
      return false;
    }
  }

  void display() {
    fill(512);
    rect(xpos, ypos, swidth, sheight);
    if(over || locked) {
      fill(900, 900, 900);
    } else {
      fill(512, 512, 512);
    }
    rect(spos-4, ypos-9, sheight+7, sheight+18);
  }

  
  int getPosScaled(float iMax) {
    // Convert spos to be values between 0 and 1
    return (int)(iMax * (spos - sposMin) / (sposMax - sposMin));
  }  
  
  void setPosScaled(float pos) {
    newspos = pos * (sposMax - sposMin) + sposMin;
  }    
}
